"""
辅助功能函数模块
- 依赖核心函数的输入输出格式
"""

import json
import pandas as pd
from tabulate import tabulate
from src.core_utils import load_field_stats, load_and_filter_city, get_missing_and_unique_stats, get_mean_table, print_mean_table, get_box_stats, print_box_stats, anova_by_year, print_anova_results

def load_field_stats(json_path):
    """加载字段统计信息（如 json 文件）"""
    if pd.notnull(json_path) and isinstance(json_path, str) and json_path:
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            if isinstance(data, dict) and "字段统计信息" in data:
                return data["字段统计信息"]
        except Exception as e:
            print(f"加载字段统计信息文件失败：{e}")
    return {}

def load_and_filter_city(csv_path, city_col="城乡", city_value="城市"):
    """读取 CSV 数据，筛选城市样本"""
    try:
        df = pd.read_csv(csv_path, low_memory=False)
        print(f"CSV文件 {csv_path} 读取成功，数据量：{df.shape[0]} 行，{df.shape[1]} 列。")
    except Exception as e:
        print(f"CSV文件读取失败：{e}")
        return None
    if city_col in df.columns:
        city_df = df[df[city_col].astype(str).str.strip() == city_value].copy()
        print(f"城市样本筛选后行数: {len(city_df)}")
        return city_df
    else:
        print(f"未找到 {city_col} 字段，无法筛选城市样本。")
        return None

def get_missing_and_unique_stats(df):
    """统计缺失率、唯一值数量，输出字段示例值"""
    missing_values = df.isnull().sum()
    unique_counts = df.nunique()
    total = len(df)
    missing_rate = missing_values / total
    return missing_rate, unique_counts
